package com.resou.reader.data.bookshelf;

import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.AddShelfResultBean;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.CommonData;
import com.resou.reader.api.entry.CommonshelfData;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.ResultList;
import com.resou.reader.api.service.UserService;
import com.resou.reader.data.bookshelf.model.BookShelfBook;
import com.resou.reader.data.bookshelf.model.ScrollNotice;
import com.resou.reader.data.bookshelf.response.DeleteResponse;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.PreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Function;
import retrofit2.Call;

public class BookshelfRepository implements BookshelfDataSource {
    private static final String TAG = "BookshelfRepository";

    private BookshelfService mService;

    /**
     * 私有构造方法，限制外部实例化存储库类
     */
    private BookshelfRepository(BookshelfService bookshelfService) {
        mService = bookshelfService;

    }

    private static BookshelfRepository sInstance;

    public static BookshelfRepository getInstance(BookshelfService bookshelfService) {
        if (sInstance == null) {
            sInstance = new BookshelfRepository(bookshelfService);
        }
        return sInstance;
    }

//    /**
//     * 添加云端的书籍到本地
//     *
//     * @param books
//     */
//    private List<BookCollection> saveToLocalBookshelf(final List<BookShelfBook> books) {
//        LitePalHelper.saveShelfBookBooks(books);
//        return LitePalHelper.loadShelfBooks();
//    }

    public List<BookCollection> clearAndLoadBooks(List<BookShelfBook> books) {
        //清空本地列表
//        LitePalHelper.clearBooks();
        //保存到本地
        LitePalHelper.saveShelfBookBooks(books);
        return LitePalHelper.loadShelfBooks();
    }

    /**
     * 添加到云端书架
     *
     * @param book   book
     * @param token  用户的token
     * @param device 设备类型
     */
    @Override
    public Observable<Result<CommonData<AddShelfResultBean>>> addToBookShelf(final BookDetailBean book, String token, String device) {
        return mService.addToBookShelf(book.getId(), token, device);
    }

    /**
     * 添加到书架
     *
     * @return
     */
//    public Observable<Result<CommonData<AddShelfResultBean>>> addToBookShelf(String token, String device) {
//
////        StringBuilder sb = new StringBuilder();
////        //拼接字符串，服务器接收的BookIdStr是一个逗号分隔的字符串
////        for (int i = 0; i < list.size(); i++) {
////            sb.append(list.get(i).getBookId());
////            //不是最后一个才添加逗号
////            if (i != list.size() - 1) {
////                sb.append(",");
////            }
////        }
////        return mService.addToBookShelf(sb.toString(), token, device);
//    }
    private String convertBookCollectionsToString(List<BookCollection> strings) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strings.size(); i++) {
            builder.append(strings.get(i).getBookId());
            //不是最后一个
            if (i != strings.size() - 1) {
                //才添加逗号
                builder.append(",");
            }
        }
        return builder.toString();
    }

    //    private String listString(List<BookShelfBook> strings) {
//        StringBuilder builder = new StringBuilder();
//        for (int i = 0; i < strings.size(); i++) {
//            builder.append(strings.get(i).getBookId());
//            //不是最后一个
//            if (i != strings.size() - 1) {
//                //才添加逗号
//                builder.append(",");
//            }
//        }
//        return builder.toString();
//    }
    private String listString(List<BookCollection> strings) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strings.size(); i++) {
            builder.append(strings.get(i).getBookId());
            //不是最后一个
            if (i != strings.size() - 1) {
                //才添加逗号
                builder.append(",");
            }
        }
        return builder.toString();
    }

    /**
     * 获取滚动栏的信息
     *
     * @param token
     * @return
     */
    public Observable<ResultList<ScrollNotice>> getScrollBulletinBoard(String token) {
        return mService.getScrollBulletinBoard(token);
    }

    /**
     * 书本详情页调用
     * 上传书籍
     *
     * @param token
     * @param freeBooks
     * @param device
     * @return
     */
    public Observable<Result> uploadBooks(String token, String freeBooks, String device) {
        return mService.uploadBooks(token, freeBooks, device);
    }


    public Observable<DeleteResponse> deleteBook(String token, String bookIdStr) {
        return mService.deleteBook(token, bookIdStr);
    }

    public Call<DeleteResponse> delete(String token, String bookIdStr) {
        return mService.delete(token, bookIdStr);
    }

//    public Observable<Result<CommonData<List<BookShelfBook>>>> loadShelfBooks(String token, int page) {
//        return mService.getShelfBooks(token, page);
//    }

//    public Observable<List<BookCollection>> loadBooks(String token, int page) {
//        //从服务器读取书本列表
//        return mService.getShelfBooks(token, page).map(result -> {
//            if (result.getCode() == 0) {
//                List<BookShelfBook> dataData = result.getData().getData();
//                return clearAndLoadBooks(dataData);
//            } else {
//                return LitePalHelper.loadShelfBooks();
//            }
//        });
//    }

    /**
     * 书籍同步，
     *
     * @param token
     * @param freeBooks
     * @param device
     * @return
     */
    public Observable<List<BookCollection>> synchronizeBooks(String token, String freeBooks, String device) {
        return mService.uploadBooks(token, freeBooks, device)
                .flatMap((Function<Result, Observable<List<BookCollection>>>) result -> getBooks(token, 0, 30));
    }

    public Observable<List<BookCollection>> getBooks(String token, int page, int pagesize) {
        return mService.getShelfBooks(token, page, pagesize)
                .flatMap((Function<Result<CommonshelfData<List<BookShelfBook>>>, Observable<List<BookCollection>>>) result -> {
                    if (result.getData().getData() == null) {
                        return Observable.just(new ArrayList<>());
                    }
                    List<BookShelfBook> shelfBooks = result.getData().getData();
                    PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).setMoney(result.getData().getUserPrice());
                    List<BookCollection> collections = new ArrayList<>();
                    for (int i = shelfBooks.size() - 1; i >= 0; i--) {
                        BookShelfBook book = shelfBooks.get(i);
                        collections.add(0, LitePalHelper.onlineShelfBkToCollectionBk(book));
                    }
                    return Observable.just(collections);
                });
    }

    /**
     * 获取封面
     *
     * @return
     */
    public Observable<BookCollection> getBooksCover() {
        return mService.getShelfBooks(UserInstance.getToken(), 0, 0)
                .flatMap((Function<Result<CommonshelfData<List<BookShelfBook>>>, Observable<BookCollection>>) result -> {
                    BookCollection bookShelfBook = new BookCollection();
                    PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).setMoney(result.getData().getUserPrice());
                    if (result.getData().getReadRecord() == null) {
                        return Observable.just(null);
                    } else {
                        bookShelfBook.setPicUrl(result.getData().getReadRecord().getCoverUrl());
                        bookShelfBook.setName(result.getData().getReadRecord().getNovelName());
                        bookShelfBook.setBookId(result.getData().getReadRecord().getNovelId());
                        bookShelfBook.setDescription(result.getData().getReadRecord().getDescription());
                        bookShelfBook.setHistoryChapterId(result.getData().getReadRecord().getChapterId());
                        bookShelfBook.setHistoryChapterName(result.getData().getReadRecord().getChapterName());
                        bookShelfBook.setChapterIndex(result.getData().getReadRecord().getChapterIndex());
                        bookShelfBook.setLastChapterName(result.getData().getReadRecord().getLastChapterName());
                    }
//                    }
                    return Observable.just(bookShelfBook);
                });
    }

    public Observable<List<BookCollection>> getBooks2(String token) {
        return mService.getShelfBooks(token, 0, -1)
                .flatMap((Function<Result<CommonshelfData<List<BookShelfBook>>>, Observable<List<BookCollection>>>) result -> {
                    List<BookShelfBook> shelfBooks = result.getData().getData();
                    PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).setMoney(result.getData().getUserPrice());
                    List<BookCollection> collections = new ArrayList<>();
                    for (int i = shelfBooks.size() - 1; i >= 0; i--) {
                        BookShelfBook book = shelfBooks.get(i);
                        collections.add(0, LitePalHelper.onlineShelfBkToCollectionBk(book));
                    }
                    return Observable.just(collections);
                });
    }
}
